(function ($) {
    var $nav = $('#main-nav');
    var $toggle = $('.toggle');
    var defaultData = {
        maxWidth: false,
        customToggle: $toggle,
        navTitle: '',
        levelTitles: false,
        insertClose: false
    };

    // we'll store our temp stuff here
    var $clone = null;
    var data = {};

    // calling like this only for demo purposes

    const initNav = function (conf) {
        if ($clone) {
            // clear previous instance
            $clone.remove();
        }

        // remove old toggle click event
        $toggle.off('click');

        // make new copy
        $clone = $nav.clone();

        // remember data
        $.extend(data, conf)

        // call the plugin
        $clone.hcMobileNav($.extend({}, defaultData, data));
    }

    // run first demo
    initNav(eval('({side:\'right\',levelOpen:false,levelSpacing:25})'));
})(jQuery);


var totalCount = 0;
var pageCount = 10;
var TagTree;
var AudioFiles;

//net
function RequestTotal() {
    websocketemit('total', { isMusic: false });
}

function RequestCarts() {
    websocketemit('getcartlist', null);
}

websocketemit('login');
RequestSearch();
RequestTips();
RequestTotal();
RequestCarts();

function RequestSearch(refresh = false) {
    isClickPageBtnToSearch = false;
    var data = {
        key: $("#inputSearch").val(),
        order: searchSort,
        index: searchPage,
        count: pageCount,
        refresh: refresh,
        isMusic: false
    }

    websocketemit('search', data);
}
//检索/排序
onwebsocket('search-sound', (data) => {
    //test data.
    AudioFiles = data.results;
    totalCount = data.size;

    var itemTemplate = "\
        <div class='audio-resource-item'>\
            <div>\
                <input id='{0}' type='checkbox' class='zoom150 pkg-item-chk audio-checkbox {6}-check'/>\
                <span class='title-name' title='{1}' style='margin-right:5px;'>{1}</span>\
                <span id='{0}' class='glyphicon glyphicon-plus' style='float:right;'></span>\
            </div>\
            <div>\
                <div style='width:500px;height:30px'>\
                    <div class='audio-play'><span id='play.{5}' suffix='{5}' class='glyphicon glyphicon-play btn-play-{6}'></span></div>\
                    <div id='waveform-{5}' style='width:400px;float:left;'></div>\
                    <div style='width:50px;float:left;'><input id='volume.{5}' suffix='{5}' type='range' class='input-range' value='1' max='2' mmin='0' step='0.2' style='transform:rotate(-90deg);text-align:center;width:100px;margin-top:35px;'/></div>\
                </div>\
                <div class='audio-resource-tags'>\
                    {3}\
                </div>\
            </div>\
        </div>\
    ";

    var htmls = "";
    for (var i = 0; i < AudioFiles.length; i++) {
        var item = AudioFiles[i];
        var tagspan = "";
        if (item.tags != undefined) {
            for (var t = 0; t < item.tags.length; t++) {
                tagspan += item.tags[t] + (t == item.tags.length - 1 ? "" : "/");
            }
        }
        tagspan += "";
        htmls += itemTemplate.format(item.id, item.name, item.suffix, tagspan, geturl(), i, 'sound');
    }   
    document.getElementById("resourceList").innerHTML = htmls;
    audioplayer = new Array(AudioFiles.length);
    for (var i = 0; i < AudioFiles.length; i++) {
        audioplayer[i] = WaveSurfer.create({
            container: '#waveform-' + i,
            waveColor: 'gray',
            progressColor: 'whitegray',
            height: 70,
        });
        var url = '{0}{1}{2}'.format(geturl(), AudioFiles[i].id, AudioFiles[i].suffix);
        audioplayer[i].load(url);
    }

    $("span.glyphicon-plus").bind("click", function () {
        BtnAddcartFileClick($(this).attr('id'));
    });
    $(".btn-play").bind("click", function () {
        let key = $(this).attr('key');
        audioplayer[key].play();
    });
    $(".input-range".format(suffix)).bind("mousemove", function () {           
        let suffix = $(this).attr('suffix');   
        CurrentAudio = Player[suffix];
        if(CurrentAudio == null)
            return;
        //设置音量
        var volumevalue = document.getElementById("volume." + suffix).value;
        CurrentAudio.setVolume(volumevalue);
    });
    if (!isClickPageBtnToSearch) {
        SetupPagination(totalCount, pageCount);
    }
});

onwebsocket('gettaglist', (data) => {
    TagTree = data;
    UpdateMainTagsShown();
});

var audioContext;
onwebsocket('play', (data) => {
    if (audioContext == undefined)
        audioContext = new AudioContext();
    audioContext.decodeAudioData(data.wav, function (buffer) {//解码成pcm流
        var audioBufferSouceNode = audioContext.createBufferSource();
        audioBufferSouceNode.buffer = buffer;
        audioBufferSouceNode.connect(audioContext.destination);
        audioBufferSouceNode.start(0);
    }, function (e) {
        alert("Fail to decode the file.");
    });
});

onwebsocket('remove', (success) => {
    if (success) {
        RequestSearch(true);
    }
    else {
        alert("delete file fail.");
    }
});

onwebsocket('totalcount', (data) => {
    $("#total").text(data.count);
});

function BtnAddcartFileClick(id) {
    var param = {
        ids: [id],
        isMusic: false
    };
    websocketemit('addcartitem', param);
}

function InputPageAmountChanged(obj) {
    pageCount = ~~$(obj).val();
    SetupPagination(totalCount, pageCount);
    RequestSearch();
}
//////////////////////全选//////////////////////////////////
var checkAll = false;
function BtnToggleClick() {
    //toggle ui
    if (checkAll == false) {//全选
        $("#sCheck").text("取消全选");
        $("#iCheck").removeClass("icon-ok");
        $("#iCheck").addClass("icon-remove");
    }
    else {//取消全选
        $("#sCheck").text("全选");
        $("#iCheck").removeClass("icon-remove");
        $("#iCheck").addClass("icon-ok");
    }
    checkAll = !checkAll;

    //logic
    $("input:checkbox").prop("checked", checkAll);
}

function GetCheckedIds() {
    var ids = [];
    $(".pkg-item-chk").each(function () {
        if ($(this).prop("checked")) {
            ids[ids.length] = $(this).attr("id");
        }
    });

    if (ids.length == 0) {
        alert("请先勾选音效，再执行操作！");
    }
    return ids;
}

function BtnAddcartAllClick() {
    var ids = GetCheckedIds();
    if (ids.length > 0) {
        var param = {
            ids: ids,
            isMusic: false
        };
        websocketemit('addcartitem', param);
    }
}

onwebsocket('addcartitem', (data) => {
    if (data == 1) {
        websocketemit('getcartlist', null);
    }
});


//搜索按钮点击事件
function BtnPageClick(page) {
    searchPage = page;
    RequestSearch();
}

function BtnSortClick(sort) {
    console.log(sort);
    searchSort = sort;

    //ui.
    $(".btnsort").removeClass("active");
    $("#" + sort).addClass("active");

    RequestSearch();
}

function BtnSearchClick() {
    RequestSearch();
}

//播放/删除/下载/收藏 按钮点击事件
function BtnPlayClick(id) {
    websocketemit('play', { isMusic: false, key: id });
}

function RequestTips() {
    websocketemit('gettaglist', { isMusic: false });
}

/////////////////////////购物车/////////////////
//setupcartlist
onwebsocket('getcartlist', (data) => {
    //cartlist
    var itemTemplate = "<li class='a'><input name='check' type='checkbox' style='width:16px;height:15px;' value='{0}' checked='true' /><span style='font-weight:bold;'> {1}</span><div style='float:right;'><span onclick='BtnPlayClick({0})' class='aduioplaybtncart'><i class='icon-play' style='margin-left:-46px;font-size:10px;'></i></span><button class='button button-circle button-tiny' style='margin-left:5px;' onclick='BtnDeleteCartItemClick('{0}')'>x</button></div>";
    var htmls = "<li class='a'><button class='button button-primary button-rounded button-small' onclick='BtnToggleCartClick()'><i id='iCheckCart' class='icon-ok'></i><span id='sCheckCart'>全选</span></button></li>";
    for (var i = 0; i < data.results.length; i++) {
        var result = data.results[i];
        var id = result.id;
        var name = result.name;
        htmls += itemTemplate.format(id, name);
    }
    htmls += "<li><div class='label'>\
                <div class='input_control_container' style='text-align:left;margin-left:20px;margin-bottom:8px;'>\
                    <span style='color:black;font-size:15px;font-weight:normal;'>截止日期:</span><input class='input_control' id=\"inputDate\" type=\"date\" value='2018-12-27' style='text-align:left;'  />\
                </div>\
                <div class='input_control_container' style='text-align:left;margin-left:20px;margin-bottom:8px;'>\
                    <span style='color:black;font-size:15px;font-weight:normal;'>项目描述:</span><input class='input_control' id=\"inputTxt\" type=\"text\" placeHolder='描述' style='text-align:left;'  />\
                </div>\
                <button class='button button-primary button-rounded btnSaveOrder' onclick='BtnCreateOrderClick();'>提交</i></button></div></li>";
    document.getElementById("cartlist").innerHTML = htmls;
})

function BtnDeleteCartItemClick(id) {
    var param = {
        ids: [id],
        isMusic: false
    };
    websocketemit('removecartitem', param);
}

onwebsocket('removecartitem', (data) => {
    if (data == 1) {
        websocketemit('getcartlist', null);
    }
})

var checkAllCart = false;
function BtnToggleCartClick() {
    //toggle ui
    if (checkAllCart == false) {//全选
        $("#sCheckCart").text("取消全选");
        $("#iCheckCart").removeClass("icon-ok");
        $("#iCheckCart").addClass("icon-remove");
    }
    else {//取消全选
        $("#sCheckCart").text("全选");
        $("#iCheckCart").removeClass("icon-remove");
        $("#iCheckCart").addClass("icon-ok");
    }
    checkAllCart = !checkAllCart;

    //logic
    $('input[name="check"]').prop('checked', checkAllCart);
}


function checkboxOnclick(button) {
    if (button.innerHTML == "全选") {
        button.innerHTML = "反选";
        $('input[name="check"]').prop('checked', 'true');
    } else {

        button.innerHTML == "全选";
        $('input[name="check"]').prop('checked', '');
    }
}
function GetAllCheckedCartId() {
    var arr = [];
    $.each($('input[name="check"]:checkbox:checked'), function () {
        arr[arr.length] = $(this).val();
    });
    return arr;
}

function BtnCreateOrderClick() {
    var desc = "";
    if ($("#inputTxt").val() != null) {
        desc = $("#inputTxt").val();
    }
    var endtime = "";
    if ($("#inputDate").val() != null) {
        endtime = $("#inputDate").val();
    }
    var arr = GetAllCheckedCartId();
    if (arr.length == 0) {
        alert("请勾选需要的音效！");
        return;
    }
    websocketemit('createorder', { desc: desc, endtime: endtime, ids: arr });
}

onwebsocket('createorder', (data) => {
    if (data == 1) {
        window.location.href = "/order";
    }
})


var CurrentMainTagButton;
var CurrentChildTagButton;

function UpdateMainTagsShown() {
    var itemTemplate = "<span><button maintag='{0}' class='btn btn-default btn-sm audio-tag-btn' style='margin:2px;'>{0}</button></span>";
    var htmls = '';
    for (let i in TagTree) {
        htmls += itemTemplate.format(i);
    }
    document.getElementById("MainTagList").innerHTML = htmls;
    $("button.audio-tag-btn").bind("click", function () {
        if (CurrentMainTagButton != undefined) {
            CurrentMainTagButton.removeClass('active');
        }
        CurrentMainTagButton = $(this);
        CurrentMainTagButton.addClass('active');
        UpdateChildTagsShown($(this).attr('maintag'));
    });
}

function UpdateChildTagsShown(childtag) {
    var htmls = "";
    var itemTemplate = "<span><button childtag='{0}' class='btn btn-default btn-sm audio-childtag-btn' style='margin:2px;'>{0}</button></span>";
    var childtags = TagTree[childtag];
    for (let i in childtags) {
        htmls += itemTemplate.format(i);
    }
    document.getElementById("ChildTagList").innerHTML = htmls;
    $("#GrandsonTagPanel").css("display", "block");
    $("button.audio-childtag-btn").bind("click", function () {
        if (CurrentChildTagButton != undefined) {
            CurrentChildTagButton.removeClass('active');
        }
        CurrentChildTagButton = $(this);
        CurrentChildTagButton.addClass('active');

        UpdateGrandsonTagsShown(CurrentChildTagButton.attr('childtag'));
    });
}

function UpdateGrandsonTagsShown(childtag) {
    var htmls = "";
    var itemTemplate = "<span><button grandsontag='{0}' class='btn btn-default btn-sm audio-grandsontag-btn' style='margin:2px;'>{0}</button></span>";
    var maintag = CurrentMainTagButton.attr('maintag');
    var grandsontags = TagTree[maintag][childtag];
    for (let i of grandsontags) {
        htmls += itemTemplate.format(i);
    }
    document.getElementById("GrandsonTagList").innerHTML = htmls;
    $("#GrandsonTagPanel").css("display", "block");
    $("button.audio-grandsontag-btn").bind("click", function () {
        $("#inputSearch").val($(this).attr('grandsontag'));
        RequestSearch();
    });
}

